<#assign object = doc.objects>
package ${object.package}.service;

import java.util.logging.Level;
import java.util.logging.Logger;
import redora.rdo.exceptions.*;
import ${object.package}.service.base.*;

public class ServiceFactory {
	private static Logger l = Logger.getLogger("${object.package}.service.ServiceFactory");

<#list object["/objects/object/name"] as modelname>
	private static ${modelname}Service ${modelname?uncap_first}; 
	private static ${modelname}ServiceJSON ${modelname?uncap_first}JSON; 
</#list>

<#list object["/objects/object/name"] as modelname>
	public static ${modelname}Service ${modelname?uncap_first}Service() throws ConnectException, QueryException {
		if (${modelname?uncap_first} != null)
			return ${modelname?uncap_first};
		else {
			l.log(Level.FINE, "Opening ${modelname}");
			${modelname}TableUpdate update = new ${modelname}TableUpdate();
			update.create();
			update.close();
			${modelname?uncap_first} = new ${modelname}Service();
			
			return ${modelname?uncap_first};
		}
	} 
	public static ${modelname}ServiceJSON ${modelname?uncap_first}ServiceJSON() throws ConnectException {
		if (${modelname?uncap_first}JSON != null)
			return ${modelname?uncap_first}JSON;
		else {
			l.log(Level.FINE, "Opening ${modelname}JSON");
			${modelname?uncap_first}JSON = new ${modelname}ServiceJSON();
			return ${modelname?uncap_first}JSON;
		}
	}
</#list>
	
	public static void tearDown() throws ConnectException {
<#list object["/objects/object/name"] as modelname>
		if (${modelname?uncap_first} != null) {
			l.log(Level.FINE, "Closing ${modelname}");
			${modelname?uncap_first}.close();
		}
		if (${modelname?uncap_first}JSON != null) {
			l.log(Level.FINE, "Closing ${modelname}JSON");
			${modelname?uncap_first}JSON.close();
		}
</#list>
	}

	@Override
	protected void finalize() throws Throwable {
		l.log(Level.FINE, "finalizing");
		tearDown();
		super.finalize();
	}
}
